package com.dcy.seataorder.biz.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dcy.seataaccount.api.api.AAccountService;
import com.dcy.seataorder.api.api.AOrderService;
import com.dcy.seataorder.api.model.OrderTbl;
import com.dcy.seataorder.biz.mapper.OrderTblMapper;
import com.dcy.db.base.service.BaseService;
import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dcy
 * @since 2021-04-23
 */
@Slf4j
@DubboService(version = "1.0.0", timeout = 3000, interfaceClass = AOrderService.class)
public class OrderTblService extends BaseService<OrderTblMapper, OrderTbl> implements AOrderService {

    @DubboReference(version = "1.0.0",check = false)
    private AAccountService aAccountService;

    /**
     * 获取表格数据
     *
     * @param orderTbl
     * @return
     */
    public IPage<OrderTbl> getPageListByEntity(OrderTbl orderTbl) {
        LambdaQueryWrapper<OrderTbl> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like(StrUtil.isNotBlank(orderTbl.getUserId()), OrderTbl::getUserId, orderTbl.getUserId());
        queryWrapper.like(StrUtil.isNotBlank(orderTbl.getCommodityCode()), OrderTbl::getCommodityCode, orderTbl.getCommodityCode());
        return super.page(orderTbl, queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    @Override
    public OrderTbl create(String userId, String commodityCode, int orderCount) {
        log.info("当前 XID: {}", RootContext.getXID());
        // 扣钱
        OrderTbl orderTblRes = null;
        boolean debit = aAccountService.debit(userId, 100);
        if (debit) {
            OrderTbl orderTbl = new OrderTbl();
            orderTbl.setUserId(userId);
            orderTbl.setCommodityCode(commodityCode);
            orderTbl.setCount(orderCount);
            orderTbl.setMoney(100d);
            // 添加订单
            if (save(orderTbl)) {
                orderTblRes = orderTbl;
            }
        }
        return orderTblRes;
    }

}
